package com.common.allCommon;

import java.io.File;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;

import com.common.otherInterface.bean.IUserInfo;
import com.product.android.commonInterface.BaseCommonStruct;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.ImageView;

/*
 * 工具类
 */
public class CommUtil {

	private static final String TAG = "CommUtil";
	public static final String LOCAL_FILE_PREFIX = "file://";

	public static final String HAS_CREATE_SHORTCUT = "hasCreateShortCut";
	
	/**
	 * 
	 * @n<b>函数名称</b>     :createShortCut
	 * @brief	创建快捷方式
	 * @see
	 * @since    Ver 1.1
	 * @param  @param act	
	 * @param  @param iconResId
	 * @param  @param appnameResId
	 * @return void
	 * @<b>作者</b>          :  huangszh
	 * @<b>创建时间</b>      :  2014-4-8下午5:33:46
	 */
	public static void createShortCut(Activity act, int iconResId,
			int appnameResId) {
		SharedPreferences sp = act.getPreferences(0);
		// 如果已经创建过了，直接赋值
		if(hasShortcut(act,act.getString(appnameResId))){
			sp.edit().putBoolean(HAS_CREATE_SHORTCUT, true).commit();
			return;
		}
		boolean hasCreat = sp.getBoolean(HAS_CREATE_SHORTCUT, false);
		if (!hasCreat) {
			Intent shortcutintent = new Intent(
					"com.android.launcher.action.INSTALL_SHORTCUT");
			// 不允许重复创建
			shortcutintent.putExtra("duplicate", false);
			// 需要现实的名称
			shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
					act.getString(appnameResId));
			// 快捷图片
			Parcelable icon = Intent.ShortcutIconResource.fromContext(
					act.getApplicationContext(), iconResId);
			shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
			// 点击快捷图片，运行的程序主入口
			Intent main = new Intent(Intent.ACTION_MAIN);
			main.addCategory(Intent.CATEGORY_LAUNCHER);
			main.setClass(act, act.getClass());
			shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,main);
			// 发送广播
			act.sendBroadcast(shortcutintent);
			sp.edit().putBoolean(HAS_CREATE_SHORTCUT, true).commit();
			
 		}
	}
	

	/**
	 * 
	 * @n<b>函数名称</b>     :hasShortcut
	 * @brief	判断是否存在快捷方式 
	 * @see
	 * @since    Ver 1.1
	 * @param  @param activity
	 * @param  @param shortcutName
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  huangszh
	 * @<b>创建时间</b>      :  2014-4-8下午5:39:40
	 */
	@TargetApi(Build.VERSION_CODES.DONUT)
    public static boolean hasShortcut(Activity activity, String shortcutName) {
        StringBuilder sbURL = new StringBuilder("content://");
        String AUTHORITY = getAuthority(activity);        
        sbURL.append(AUTHORITY).append("/favorites?notify=true");
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = resolver.query(Uri.parse(sbURL.toString()), null, "title=?",
                new String[] { shortcutName }, null);
        if (cursor != null && cursor.moveToFirst()) {
            Log.i("shortcut", "has shortcut");
            cursor.close();
            return true;
        }
        return false;
    }
	
	/**
	 * 获取contentresolver的AUTHORITY
	 * 
	 * <br>Created 2014-11-19 下午6:50:42
	 * @param activity 页面
	 * @return         AUTHORITY
	 * @author       linsj
	 */
	private static String getAuthority(Activity activity){
	    //先获取特定机型
	    String AUTHORITY = getParticalMobileAuthority();
	    //找不到就查所有包的权限
	    if(TextUtils.isEmpty(AUTHORITY)){
	        AUTHORITY = getAuthorityFromPermission(activity.getApplicationContext());
	        //再找不到就用默认
	        if (TextUtils.isEmpty(AUTHORITY)) {
	            int systemversion = android.os.Build.VERSION.SDK_INT;
	            if (systemversion < 8) {
	                AUTHORITY = "com.android.launcher.settings";
	            } else {
	                AUTHORITY = "com.android.launcher2.settings";
	            }
	        }
	    }	            
        
        return AUTHORITY;
	}
	
	/**
	 * 获取特定型号机型的AUTHORITY
	 * 
	 * <br>Created 2014-11-19 下午6:45:19
	 * @return     AUTHORITY
	 * @author       linsj
	 */
	private static String getParticalMobileAuthority(){
	    if(-1 != Build.MODEL.toLowerCase().indexOf("htc")){
	        return "com.htc.launcher.settings";
	    }
	    
	    return null;
	}
	
	/**
	 * 指定Permission以获取Authority
	 * 
	 * <br>Created 2014-11-19 下午6:53:41
	 * @param context  上下文
	 * @return         Authority
	 * @author       linsj
	 */
    private static String getAuthorityFromPermission(Context context) {
        final String READ_SETTINGS = "com.android.launcher.permission.READ_SETTINGS";
        List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(
                PackageManager.GET_PROVIDERS);
        if (packs == null) {
            return null;
        }
        
        return getPackageAuthority(packs, READ_SETTINGS);
    }
    
    /**
     * 读取包里的Authority
     * 
     * <br>Created 2014-11-19 下午6:53:17
     * @param packs         包列表
     * @param permission    指定权限
     * @return              Authority
     * @author       linsj
     */
    private static String getPackageAuthority(final List<PackageInfo> packs, String permission) {
        for (PackageInfo pack : packs) {
            ProviderInfo[] providers = pack.providers;
            if (providers != null) {
                for (ProviderInfo provider : providers) {
                    if (permission.equals(provider.readPermission)
                            || permission.equals(provider.writePermission)) {
                        return provider.authority;
                    }
                }
            }
        }
        
        return null;
    }

	/**
	 * 
	 * @n<b>函数名称</b>     :getImgLocalPathByUri
	 * @brief	根据图片URI获取本地存放路径
	 * @see
	 * @since    Ver 1.1
	 * @param  @param context
	 * @param  @param imageUri
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  huangszh
	 * @<b>创建时间</b>      :  2013-12-25下午2:58:05
	 */
	public static String getImgLocalPathByUri(Context context,Uri imageUri){
		if (imageUri == null) return null;
		// 获取文件的绝对路径  相册
		String path = "";
		String[] projection = { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE };
		Cursor cursor = MediaStore.Images.Media.query(context.getContentResolver(), imageUri, projection);
		try{						
			if (cursor != null && cursor.moveToNext()) {
				path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
			}else{                    //小米1
				path=imageUri.getPath();
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}finally {
			if (cursor != null)
                cursor.close();
		}
		return path;
	}
	
	/**
	 * 
	 * @n<b>函数名称</b>     :millsec2Sec
	 * @brief                语音的长度毫秒改成秒, 如果有余数加1
	 * @see
	 * @since    Ver 1.1
	 * @param  @param time
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2014-4-16下午3:33:44
	 */
	public static int  millsec2Sec(long time){		
		return Double.valueOf(Math.ceil(time/1000.0)).intValue();
	}

	/**
	 * 格式化double类型为特定格式的字符串.
	 * 
	 * @param double d 双精度数字
	 * @param int dot 后跟小数点位数
	 * @return String 返回特定格式的字符串
	 */
	public static String formatNumber(double d, int dot) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(dot);
		nf.setMaximumFractionDigits(dot);
		if (d > 1073741824) {
			d = d / 1073741824.0;
			return nf.format(d) + "GB";
		} else if (d > 1048576) {
			d = d / 1048576.0;
			return nf.format(d) + "MB";
		} else
			d = d / 1024.0;
		return nf.format(d) + "KB";
	}

	/**
	 * 格式化String为double型，如果字符串为空，返回0.
	 * 
	 * @param String
	 *            s 双精度数字
	 * @return double 返回double类型数值
	 */
	public static double parseDouble(String s) {
		double d = 0;
		if (s != null) {
			try {
				d = Double.parseDouble(s);
			} catch (NumberFormatException e) {
				try {
					String t = s.replaceAll(",", "");
					d = Double.parseDouble(t);
				} catch (NumberFormatException e2) {
					d = 0;
				}
			}
		}
		return d;
	}

	/**
	 * 格式化String为double型，如果字符串为空，返回0.
	 * 
	 * @param String
	 *            s 双精度数字
	 * @return double 返回double类型数值
	 */
	public static double parseRelugarDouble(String s) {
		double relvalue;
		int index;
		if (s == null || s.equals(""))
			return 0;
		else {
			if ((index = s.indexOf("K")) != -1) {
				relvalue = parseDouble(s.substring(0, index)) * 1024;
				return relvalue;
			} else if ((index = s.indexOf("M")) != -1) {
				relvalue = parseDouble(s.substring(0, index)) * 1048576;
				return relvalue;
			} else if ((index = s.indexOf("G")) != -1) {
				relvalue = parseDouble(s.substring(0, index)) * 1073741824;
				return relvalue;
			} else
				return 0;
		}
	}

	/**
	 * 返回两个Date对象的之间的分钟数
	 * 
	 * @param Date
	 *            date1 作为被减数的Date对象
	 * @param Date
	 *            date2 作为减数的Date对象
	 * @return int 两个Date对象的之间的分钟数
	 */
	public static int getMinutesTween(Date date1, Date date2) {
		long mill1 = date1.getTime();
		long mill2 = date2.getTime();
		return (int) Math.ceil((mill1 - mill2) * 1.0 / (1000 * 60));
	}

	public static int getMinutesTween(long mill1, long mill2) {
		return (int) Math.ceil((mill1 - mill2) * 1.0 / (1000 * 60));
	}

	public static int getSecondsTween(long mill1, long mill2) {
		return (int) Math.ceil((mill1 - mill2) * 1.0 / 1000);
	}

	/**
	 * 格式化String为int型，如果字符串为空，返回0.
	 * 
	 * @param String
	 *            双精度数字
	 * @return int 返回int类型数值
	 */
	public static int parseInt(String s) {
		int i = 0;
		if (s != null) {
			try {
				i = Integer.parseInt(s);
			} catch (NumberFormatException e) {
				i = 0;
				double t = parseDouble(s);
				if (t != 0) {
					i = (int) t;
				}
				// logger.error(e.getMessage());
			}
		}
		return i;
	}

	/**
	 * 格式化String为int型，如果字符串为空，返回0.
	 * 
	 * @param String
	 *            双精度数字
	 * @return int 返回int类型数值
	 */
	public static long parseLong(String s) {
		long i = 0l;
		if (s != null) {
			try {
				i = Long.parseLong(s);
			} catch (NumberFormatException e) {
				i = 0l;
				double t = parseDouble(s);
				if (t != 0) {
					i = (long) t;
				}
			}
		}
		return i;
	}

	/**
	 * 删除目录
	 * 
	 * @param dir
	 * @return
	 */
	public static boolean deleteDir(File objDir) {
		File[] objarySubfs = objDir.listFiles();
		if (objarySubfs == null)
			return false;
		for (int i = 0; i < objarySubfs.length; i++) {
			if (objarySubfs[i].isFile()) {
				objarySubfs[i].delete();
			} else {
				deleteDir(objarySubfs[i]);
			}
		}
		return objDir.delete();
	}
	
	   public static String getTime(long timeStamp) {
	    	String time=
	         getTimeFormat(
	                "yyyy-MM-dd HH:mm",
	                timeStamp 
	                * (timeStamp < 10000000000L ? 1000 : 1)
	                        + TimeZone.getTimeZone("GMT+8:00 ").getRawOffset()
	                        - TimeZone.getDefault().getRawOffset());
	    	if(time!=null&&time.indexOf(getCurrentYear())!=-1){
	    		time=time.substring(5);
	    	}
	    	return time;
	    }
	    public static String getTimeFormat(String format, long time) {
	        SimpleDateFormat formatter = new SimpleDateFormat(format);
	        Date curDate = new Date(time);// 获取当前时间
	        return formatter.format(curDate);
	    }

	/**
	 * 返回秒
	 * 
	 * @return long
	 */
	public static String getSeconds(long now, long beg) {

		return formatDoubleNumber((now - beg) / 1000.0, 2);
	}

	/**
	 * 格式化double类型为特定格式的字符串.
	 * 
	 * @param double d 双精度数字
	 * @param int dot 后跟小数点位数
	 * @return String 返回特定格式的字符串
	 */
	public static String formatDoubleNumber(double d, int dot) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(dot);
		nf.setMaximumFractionDigits(dot);
		return nf.format(d);
	}

	/**
	 * 返回当前时间,格式HH:mm:ss
	 * 
	 * @return String 当前时间
	 */
	public static String getCurrentDateTime(Date date) {
		if (date == null)
			return "";
		String strTime = null;
		try {
			DateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			strTime = objMyformat.format(date);
		} catch (Exception e) {
			System.out.println("CommUtil.getCurrentDateTime" + e);
		}
		return strTime;
	}

	public static String getCurrentDateTime() {
		String strTime = null;
		try {
			DateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			strTime = objMyformat.format(new Date());
		} catch (Exception e) {
			System.out.println("CommUtil.getCurrentDateTime" + e);
		}
		return strTime;
	}

	public static String getCurrentDate() {
		String strTime = null;
		try {
			DateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd");
			strTime = objMyformat.format(new Date());
		} catch (Exception e) {
			System.out.println("CommUtil.getCurrentDateTime" + e);
		}
		return strTime;
	}

	/**
	 * 返回当前时间,格式HH:mm:ss
	 * 
	 * @return String 当前时间
	 */
	public static String getDateTime(Date date) {
		if (date == null) {
			return "";
		}
		String strTime = "";
		try {
			if (getDayDiffFromToday(date)) { // 如果是今天
				strTime = getCurrentTime(date);
			} else {
				DateFormat objMyformat = new SimpleDateFormat("yyyy-MM-dd");
				strTime = objMyformat.format(date);
			}
		} catch (Exception e) {
			strTime = "";
		}
		return strTime;
	}
	
//    public static Date getDate(int timeStamp) {
//    	long time=timeStamp* (timeStamp < 10000000000L ? 1000 : 1)
//                + TimeZone.getTimeZone("GMT+8:00 ").getRawOffset()
//                - TimeZone.getDefault().getRawOffset();
//    	 Date curDate = new Date(time);// 获取当前时间
//    	return curDate;
//    }
    
	/**
	 * 返回当前时间,格式HH:mm:ss
	 * 
	 * @return String
	 */
	public static String getDuration(Date date, long endtime) {
		if (date == null) {
			return "";
		}
		int durationSeconds = (int) Math
				.ceil((endtime - date.getTime()) * 1.0 / 1000);
		// Log.v(TAG,"date : "+date.getTime() +"endtime: "+endtime
		// +"durationSeconds: "+durationSeconds);
		int hours = durationSeconds / (60 * 60);
		int leftSeconds = durationSeconds % (60 * 60);
		int minutes = leftSeconds / 60;
		int seconds = leftSeconds % 60;

		StringBuffer sBuffer = new StringBuffer();
		if (hours > 0) {
			sBuffer.append(addZeroPrefix(hours));
			sBuffer.append(":");
		}
		sBuffer.append(addZeroPrefix(minutes));
		sBuffer.append(":");
		sBuffer.append(addZeroPrefix(seconds));
		return sBuffer.toString();
	}

	public static String addZeroPrefix(int number) {
		if (number < 10) {
			return "0" + number;
		} else {
			return "" + number;
		}
	}

	/**
	 * 截取字符串并加省略号
	 * 
	 * @return String
	 */
	public static String getSubString(String inStr, int len) {
		if (inStr == null) {
			return "";
		}
		if (inStr.length() > len) {
			inStr = inStr.substring(0, len - 2) + "..";
		}
		return inStr;
	}

	/**
	 * 根据指定分隔拆分字符串，返回字符串数组。 不剔出空字符串 例： String[] s = strBreak("a.b.c..d",".");
	 * //s为{"a","b","c","","e"}
	 * 
	 * @param array
	 * @param str
	 * @return
	 */
	public static String[] strBreakWithBlank(String str, String delim) {
		if (isBlank(str) || delim == null)
			return null;
		String[] strArray = str.split("\\" + delim);
		return strArray;
	}

	public static int getYear(String dateStr) {
		if (dateStr == null || dateStr.length() < 4)
			return parseInt(getCurrentYear());
		String year = dateStr.substring(0, 4);
		return parseInt(year);
	}

	/**
	 * 取出日期时间中的日期
	 * 
	 * @param dt
	 *            时间日期 "YYYY-MM-DD HH:mm:ss"
	 * @return 时间 YYYY-MM-DD
	 */
	public static String getDateOfDT(String dt) {
		String date = "";
		if (!isBlank(dt)) {
			if (dt.length() <= 10) {
				date = dt;
			} else {
				date = dt.substring(0, 10);
			}
		}
		return date;
	}

	/**
	 * 返回日期的月
	 * 
	 * @param dateStr
	 *            输入的字符串 格式YYYY-MM-DD
	 * @return int 月
	 */
	public static int getMonth(String dateStr) {
		if (dateStr == null || dateStr.length() < 7)
			return getCurrentMonth();
		String month = dateStr.substring(5, 7);
		return parseInt(month);
	}
	/**
	 * 格式化String为int型，如果字符串为空，返回0.
	 * 
	 * @param String
	 *            s 双精度数字
	 * @return int 返回int类型数值
	 */
	public static int parseDayInt(String s) {
		int i = 0;
		if (s != null) {
			try {
				i = Integer.parseInt(s);
				if (i == 0) {
					return 1;
				}
			} catch (NumberFormatException e) {
				i = 0;
				double t = parseDouble(s);
				if (t != 0) {
					i = (int) t;
				}
			}
		}
		return i;
	}

	/**
	 * 判断字符串是否为空或空串；其中空串是指经过trim后字符串长度为0。 为空或空串返回true，否则返回false。
	 * 
	 * @param str
	 * @return
	 */

	public static boolean isBlank(String str) {
		if (str == null || (str.trim()).equals(""))
			return true;
		return false;
	}

	/*
	 * 验证是否为数字
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	/**
	 * 
	 * 验证是否是手机号码
	 * 
	 * @param str
	 * 
	 * @return
	 */

	public static boolean isMobile(String str) {
		if ("".equals(str))
			return true;
		Pattern pattern = Pattern.compile("1[0-9]{10}");
		Matcher matcher = pattern.matcher(str);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 匹配国内电话号码：\d{3}-\d{8}|\d{4}-\d{7} 匹配形式如 0511-4405222 或 021-87888822
	 */
	public static boolean isTelephone(String str) {
		if ("".equals(str))
			return true;
		Pattern pattern = Pattern.compile("([0-9]{3,4}-?)?[0-9]{7,8}");
		Matcher matcher = pattern.matcher(str);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 验证字符串是否是email
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmail(String str) {
		if ("".equals(str))
			return true;
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_\\.-])+@(([a-zA-Z0-9-])+\\.)+([a-zA-Z0-9]{2,4})+$");

		Matcher matcher = pattern.matcher(str);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	public static String getShowTime(int totalcount) {
		if (totalcount == 0)
			return "00:00";
		StringBuffer showtime = new StringBuffer();
		if (totalcount % 60 < 10 && totalcount / 60 < 10) {
			showtime.append("0");
			showtime.append(totalcount / 60);
			showtime.append(":0");
			showtime.append(totalcount % 60);
		} else if (totalcount % 60 > 9 && totalcount / 60 < 10) {
			showtime.append("0");
			showtime.append(totalcount / 60);
			showtime.append(":");
			showtime.append(totalcount % 60);
		} else if (totalcount % 60 < 10 && totalcount / 60 > 9) {
			showtime.append(totalcount / 60);
			showtime.append(":0");
			showtime.append(totalcount % 60);
		} else {
			showtime.append(totalcount / 60);
			showtime.append(":");
			showtime.append(totalcount % 60);
		}
		return showtime.toString();
	}

	/**
	 * 判断给定日期是否为当天，
	 * 
	 * @param dt
	 * @param type
	 *            0--当天
	 * @return
	 */
	public static boolean getDayDiffFromToday(Date dt) {
		Date today = new Date();
		today.setHours(23);
		today.setMinutes(59);
		today.setSeconds(59);

		long diff = today.getTime() - dt.getTime();
		if (diff < 0)
			diff = 0;
		long days = diff / (1000 * 60 * 60 * 24);
		if (days == 0)
			return true;
		return false;
	}

	/**
	 * 返回当前时间,格式HH:mm
	 * 
	 * @return String 当前时间
	 */
	public static String getCurrentTime(Date date) {
		String time = "";
		try {
			DateFormat myformat = new SimpleDateFormat("HH:mm");
			time = myformat.format(date);
		} catch (Exception e) {
			System.out.println(e);
		}
		return time;
	}

//	/**
//	 * 判断是否合法日期 允许2005-1-1，2005-01-01
//	 * 
//	 * @param value
//	 * @return
//	 */
//	public static String checkValidDate(String value, String format) {
//		Log.v(TAG, "value:" + value);
//		if (isBlank(value)) {
//			return null;
//		}
//		try {
//			SimpleDateFormat formatter = new SimpleDateFormat(format);
//			Date day = formatter.parse(value);
//			String date = formatter.format(day);
//			if (value.equals(date)) {
//				return value;
//			}
//			int idx1 = value.indexOf("-");
//			int idx2 = value.indexOf("-", idx1 + 1);
//			if (idx1 < 0 || idx2 < 0 || idx2 <= idx1) {
//				return null;
//			}
//			String y = value.substring(0, idx1);
//			String m = value.substring(idx1 + 1, idx2);
//			String d = value.substring(idx2 + 1);
//			if (parseInt(y) == getYear(date) && parseInt(m) == getMonth(date)
//					&& parseInt(d) == getDay(date)) {
//				return date;
//			} else if (parseInt(y) == getYear(date)
//					&& parseInt(m) == (getMonth(date) - 5)
//					&& parseInt(d) == getDay(date)) {
//				return value;
//			}
//			return null;
//		}catch(StringIndexOutOfBoundsException e){
//			Log.e(TAG, "checkValidDate index out of bounds");
//			e.printStackTrace();
//			return null;
//		} catch (Exception e) {
//			return null;
//		}
//	}

	/**
	 * 返回当前年 格式YYYY
	 * 
	 * @return String 年
	 */
	public static String getCurrentYear() {
		String year = null;
		try {
			DateFormat myformat = new SimpleDateFormat("yyyy-MM-dd");
			String date = myformat.format(new Date());
			year = date.substring(0, 4);
		} catch (Exception e) {
			System.out.println(e);
		}
		return year;
	}

	/**
	 * 返回当前年 格式
	 * 
	 * @return String M
	 */
	public static int getCurrentMonth() {
		int month = 12;
		try {
			DateFormat myformat = new SimpleDateFormat("yyyy-MM-dd");
			String date = myformat.format(new Date());
			month = parseInt(date.substring(5, 7));
		} catch (Exception e) {
			System.out.println(e);
		}
		return month;
	}

	/**
	 * 返回日期的日
	 * 
	 * @param dateStr
	 *            输入的字符串 格式YYYY-MM-DD
	 * @return int 日
	 */
	public static int getCurrentDay() {
		int day = 0;
		try {
			DateFormat myformat = new SimpleDateFormat("yyyy-MM-dd");
			String date = myformat.format(new Date());
			day = parseInt(date.substring(8, 10));
		} catch (Exception e) {
			System.out.println(e);
		}
		return day;
	}

	public static String getHourMinute(int hourOfDay, int minute) {
		StringBuffer rec = new StringBuffer();
		String s="";
		switch (hourOfDay / 6) {
		case 0:
		case 1:
			s=" AM";
			break;
		case 2:
		case 3:		
			if(hourOfDay!=12){
				hourOfDay=hourOfDay-12;
			}
			s=" PM";
			break;
		}
		if(hourOfDay==0){
			hourOfDay=12;
		}
		rec.append(addZeroPrefix(hourOfDay));
		rec.append(":");
		rec.append(addZeroPrefix(minute));
		rec.append(s);
		return rec.toString();
	}

	// public static boolean isBetweenPeriod() {
	// return isBetweenPeriod(GlobalVariable.getInstance().getCommonconfig()
	// .getReceivestart_hour(), GlobalVariable.getInstance()
	// .getCommonconfig().getReceivestart_minute(), GlobalVariable
	// .getInstance().getCommonconfig().getReceiveend_hour(),
	// GlobalVariable.getInstance().getCommonconfig()
	// .getReceiveedn_minute());
	// }

	public static boolean isBetweenPeriod(int hour1, int minute1, int hour2,
			int minute2) {
		if(hour1==0){
			hour1=12;
		}else if(hour1==12){
			hour1=0;
		}
		if(hour2==0){
			hour2=12;
		}else if(hour2==12){
			hour2=0;
		}
		Date date = new Date();
		int src = date.getHours() * 60 + date.getMinutes();
		int time1 = hour1 * 60 + minute1;
		int time2 = hour2 * 60 + minute2;
//		 Log.v(TAG,"hour1:"+hour1 +" hour2:"+hour2+" date.getHours():"+date.getHours());
//		 Log.v(TAG,"src:"+src +" time1:"+time1 +" time2:"+time2);
		if (time2 > time1) {
			if (src >= time1 & time2 >= src) {
				return true;
			} else {
				return false;
			}
		} else if (time1 == time2) {
			return true;
		} else {
			if (src > time2 & time1 > src) {
				return false;
			} else {
				return true;
			}
		}

	}
	
	/**
	 * 检查当前时间是否位于两个时间之前，使用24小时制
	 * <br>Created 2014-5-14 下午11:43:48
	 * @param hour1		开始时间小时
	 * @param minute1	开始时间分钟
	 * @param hour2		结束时间小时
	 * @param minute2	结束时间分钟
	 * @return			是否位于两个小时之间
	 * @author        :  linsj
	*/
	public static boolean isBetweenPeriodEx(int hour1, int minute1, int hour2,
			int minute2) {
		// 取得时间所代表的分钟数
		int iMinuteCount1 = hour1 * 60 + minute1;
		int iMinuteCount2 = hour2 * 60 + minute2;

		// 取得当前时间
		Date date = new Date();
		int iCurMinutePast = date.getHours() * 60 + date.getMinutes();

		// 如果两个时间相等，就是全天候啦
		if (iMinuteCount2 == iMinuteCount1) {
			return true;
		}

		// 如果结束时间小于开始时间，说明是第二天，要加上一天
		if (iMinuteCount2 < iMinuteCount1) {
			iMinuteCount2 += 24 * 60;
		}

		// 如果当前时间位于开始时间与结束时间之前
		if (iCurMinutePast > iMinuteCount1 && iMinuteCount2 > iCurMinutePast) {
			return true;
		}

		return false;
	}

	/**
	 * 返回两个Date对象的之间的秒数(往返一个消息不超过30s,认为失败)
	 * 
	 * @param Date
	 *            date1 作为被减数的Date对象
	 * @param Date
	 *            date2 作为减数的Date对象
	 * @return int 两个Date对象的之间的秒数
	 */
	public static boolean getSecondTween(String date2, int outtime) {
		long mill1 = System.currentTimeMillis();
		long mill2 = Long.parseLong(date2);
		if ((int) ((mill1 - mill2) / (1000)) >= outtime) {
			return true;
		}
		return false;
	}
	public static long generateLong(){
		return  System.currentTimeMillis()*new Random().nextInt(10000);
	}

	/**
	 * 
	 * @n<b>函数名称</b>     :generate
	 * @brief　　生成唯一字段
	 * @see
	 * @since    Ver 1.1
	 * @param  @param type
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2013-11-13下午3:54:54
	 */
	public static String generate(int type) {
		return new StringBuffer().append(System.currentTimeMillis())
				.append("-").append(type).append(UUID.randomUUID()).toString();
	}
	
	public static String generate() {
		return new StringBuffer().append(System.currentTimeMillis())
				.append("-").append(UUID.randomUUID()).toString();
	}
	
    
	/**
	 * 
	 * @n<b>函数名称</b>     :getcurrentTimeMillis
	 * @brief   从gid中获取时间
	 * @see
	 * @since    Ver 1.1
	 * @param  @param guid
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2013-11-13下午3:54:29
	 */
	public static String getcurrentTimeMillis(String guid) {
		if (isBlank(guid))
			return null;
		int index = guid.indexOf("-");
		if (index != -1) {
			return guid.substring(0, index);
		} else {
			return null;
		}
	}
	
	/**
	 * 
	 * @n<b>函数名称</b>     :getCategoryFromGenerateId
	 * @brief  从gid中获取type
	 * @see
	 * @since    Ver 1.1
	 * @param  @param guid
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2013-11-13下午3:59:25
	 */
	public static int getCategoryFromGenerateId(String guid){
		if (isBlank(guid))
			return 0;
		int index=guid.indexOf("-");
		if(index!=-1 && index+1 < guid.length()){
			return parseInt(guid.substring(index+1, index+2));
		}
		return 0;
	}

	/*
	 * 判断网络状态
	 */
	public static boolean JudgeNetWorkStatus(Context context) {
		if (context==null){
			return false;
		}
		boolean netStatus = false;
		ConnectivityManager conManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info=conManager.getActiveNetworkInfo();
		if (info!= null) {
			netStatus = info.isAvailable();
		}
		// Log.w(TAG, "网络是否连接异常netStatus :" + netStatus);
		return netStatus;
	}

	
	public static String getAge(String birthday){
		long long1  =0;
		try{
			long1 = Date.parse(birthday.replace("-","/"));
		}
		catch(RuntimeException e){
			return "";
		}
		Calendar calendar = Calendar.getInstance();
		Date date = calendar.getTime();
		int year1 = date.getYear() ;
		int month1 = date.getMonth();
		int day1 = date.getDate();
		
		calendar.setTimeInMillis(long1);
		date = calendar.getTime();
		
		int year2 = date.getYear();
		int month2 = date.getMonth();
		int day2 = date.getDate();
		
		int yearDiff = year1-year2;
		int monthDiff = (month1-month2)+(day1-day2>=0?0:(-1));
		yearDiff = yearDiff+ (monthDiff>=0?0:-1);
		return yearDiff>0?(yearDiff+""):"0";
		
	}

	/**
	 * @n<b>函数名称</b>     :getKey
	 * @brief 根据URL获取KEY
	 * @see
	 * @since    Ver 1.2
	 * @param  @param url
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-8-5下午3:39:36      
	*/
	public static String getKey(String url){
		String[] keys=url.split("&");
		try {
			String key=keys[1].replace("k=", "");
			return key;
		} catch (Exception e) {
			return "";
		}
	}
	
	/**
	 * 判断url是否为http或ftp协议URL,对于非ftp或http协议的URL，添加http协议头
	 * @n<b>函数名称</b>     :completeUrl
	 * @brief
	 * @see
	 * @since    Ver 1.1
	 * @param  @param url  原始url
	 * @param  @return 添加协议头的url
	 * @return String
	 * @<b>作者</b>          :  zxq
	 * @<b>创建时间</b>      :  2013-11-25下午5:05:06
	 */
	public static String completeUrl(String url) {
		if (TextUtils.isEmpty(url)) {
			return "";
}
		if (!url.startsWith("ftp") && !url.startsWith("Ftp") && !URLUtil.isNetworkUrl(url)) {
			return "http://" + url;
		}
		return url;
	}
	
	private static String[] prefixes = new String[] { "http://", "https://", "rtsp://"};
	
	/**
	 * 
	 * @n<b>函数名称</b>     :makeUrl
	 * @brief	对没有http，https头的url添加头部
	 * @see
	 * @since    Ver 1.1
	 * @param  @param url
	 * @param  @param prefixes
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  huangszh
	 * @<b>创建时间</b>      :  2013-12-20下午5:31:35
	 */
	public static final String makeUrl(String url) {

		if(!url.startsWith("ftp") && !url.startsWith("Ftp") ){
			boolean hasPrefix = false;
		        
	        for (int i = 0; i < prefixes.length; i++) {
	            if (url.regionMatches(true, 0, prefixes[i], 0,
	                                  prefixes[i].length())) {
	                hasPrefix = true;

	                // Fix capitalization if necessary
	                if (!url.regionMatches(false, 0, prefixes[i], 0,
	                                       prefixes[i].length())) {
	                    url = prefixes[i] + url.substring(prefixes[i].length());
	                }

	                break;
	            }
	        }

	        if (!hasPrefix) {
	            url = prefixes[0] + url;
	        }
		}
        return url;
    }
	
	/**
	 * 判断url是否Gif图片
	 * @n<b>函数名称</b>     :isGifPicture
	 * @brief
	 * @see
	 * @since    
	 * @param  @param url  原始url
	 * @param  @return 添加协议头的url
	 * @return String
	 * @<b>作者</b>          :  chenqian
	 * @<b>创建时间</b>      :  2013-12-16下午15:20:06
	 */
	public static boolean isGifPicture(String strFile) {
		if (!TextUtils.isEmpty(strFile) && (strFile.toLowerCase().endsWith(".gif") || strFile.toLowerCase().contains(".gif&"))) {
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * @n<b>函数名称</b>     :isGifForWeibo
	 * @brief
	 * @see
	 * @since    Ver 1.1
	 * @param  @param image_ext
	 * @param  @return
	 * @return boolean
	 * @<b>作者</b>          :  chenqian
	 * @<b>创建时间</b>      :  2014-3-24下午8:52:26
	 */
	public static boolean isGifForWeibo(String image_ext, String url){
		if(!TextUtils.isEmpty(image_ext) && TextUtils.equals(image_ext.toLowerCase(), "gif")){
			return true;
		}
		return CommUtil.isGifPicture(url);
	}

	/**
	 * @n<b>函数名称</b>     :getIntFromXml
	 * @brief 从XML里面读INT型数据
	 * @see
	 * @version    Ver 1.3.x
	 * @param  @param xmlPull
	 * @param  @param key
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-1-16下午9:25:23      
	*/
	public static int getIntFromXml(XmlPullParser xmlPull,String key){
		int result=0;
		String value=xmlPull.getAttributeValue("", key);
		if (!TextUtils.isEmpty(value)){
			try {
				result=Integer.parseInt(value);		
			} catch (NumberFormatException e) {
			}
		}
		return result;
	}
	
	/**
	 * 从异步线程发出的消息中取出用户资料和ImageView的tag（uid）对比，匹配则用消息中fid重载头像
	 * 
	 * <br>Created 2014-11-27 上午11:59:06
	 * @param struct 消息
	 * @param imageView 图片展示控件
	 * @author       ChuXY
	 */
	public static void updateSculptureImageShown(BaseCommonStruct struct,
			ImageView imageView) {
		if (imageView == null || imageView.getTag() == null
				|| !(imageView.getTag() instanceof Long)) {
			return;
		}
		if (struct != null && struct.bPara && struct.obj1 != null
				&& struct.obj1 instanceof IUserInfo) {
			IUserInfo userInfo = ((IUserInfo) struct.obj1);
			long uid = userInfo.getUid();
			long fileId = userInfo.getFileId();
			if ((Long) (imageView.getTag()) == uid && fileId >= 0) {
				StarAppHeadImageLoader.displayCircleImageByFileId(fileId,
						StarAppHeadImageLoader.IMAGE_TYPE_HEAD_100, imageView,
						null);
				
			}
		}
	}
}
